<template>
  <div class="history-container">
    <!-- 工单统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon water-icon">
              <el-icon><Finished style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">累计完成订单</div>
              <div class="stat-value">{{ stats.totalCompleted }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon repair-icon">
              <el-icon><Star style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">已获得评价</div>
              <div class="stat-value">{{ stats.totalRated }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rating-icon">
              <el-icon><StarFilled style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均评分</div>
              <div class="stat-value">{{ stats.averageRating.toFixed(1) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h2>历史记录</h2>
              <div class="header-actions">
                <el-select v-model="filterStatus" placeholder="状态" size="small" style="width: 100px; margin-right: 10px">
                  <el-option label="全部" value="" />
                  <el-option label="已送达" value="已送达" />
                  <el-option label="已评价" value="已评价" />
                </el-select>
                <el-select v-model="ratingFilter" placeholder="评分" size="small" style="width: 100px; margin-right: 10px">
                  <el-option label="全部" value="" />
                  <el-option label="5星" value="5" />
                  <el-option label="4星" value="4" />
                  <el-option label="3星" value="3" />
                  <el-option label="2星" value="2" />
                  <el-option label="1星" value="1" />
                  <el-option label="未评分" value="0" />
                </el-select>
                <el-button type="primary" size="small" @click="fetchCompletedTasks">查询</el-button>
                <el-button size="small" @click="resetFilters">重置</el-button>
              </div>
            </div>
          </template>

          <el-table :data="completedTasks" border style="width: 100%" v-loading="loading" height="500">
            <el-table-column prop="completed_time" label="完成时间" width="180" sortable />
            <el-table-column prop="type" label="任务类型" width="100">
              <template #default="scope">
                <el-tag :type="getTaskTypeTag(scope.row.type)">
                  {{ getTaskTypeName(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="任务内容" show-overflow-tooltip width="240">
              <template #default="scope">
                <template v-if="scope.row.type === 'water'">
                  <span v-if="scope.row.product_name && scope.row.quantity">
                    {{ scope.row.product_name }} x{{ scope.row.quantity }}
                  </span>
                  <span v-else>{{ scope.row.content }}</span>
                </template>
                <template v-else-if="scope.row.type === 'repair'">
                  {{ scope.row.fault_description || scope.row.content }}
                </template>
                <template v-else-if="scope.row.type === 'cleaning'">
                  {{ scope.row.special_requirements || scope.row.content || '标准保洁' }}
                </template>
                <template v-else>
                  {{ scope.row.content }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="配送/服务地址" width="300" show-overflow-tooltip />
            <el-table-column prop="rating" label="评分" width="150" align="center" sortable>
              <template #default="scope">
                <el-rate v-model="scope.row.rating" disabled size="small" v-if="scope.row.rating > 0"/>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已评价' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewTaskDetail(scope.row)" type="primary" text>查看</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @size-change="handleSizeChange"
              @current-page-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 按任务类型统计 - 只对管理员显示 -->
    <!-- <el-row :gutter="20" style="margin-top: 20px" v-if="userRole === '管理员'">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>按任务类型统计</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="type-stat-card water-bg">
                <div class="type-stat-icon">
                  <el-icon><MugTea style="font-size: 24px" /></el-icon>
                </div>
                <div class="type-stat-info">
                  <div class="type-stat-title">送水任务</div>
                  <div class="type-stat-value">{{ stats.waterTasks }}</div>
                  <div class="type-stat-sub">平均评分: {{ stats.waterRating.toFixed(1) }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="type-stat-card repair-bg">
                <div class="type-stat-icon">
                  <el-icon><Service style="font-size: 24px" /></el-icon>
                </div>
                <div class="type-stat-info">
                  <div class="type-stat-title">维修任务</div>
                  <div class="type-stat-value">{{ stats.repairTasks }}</div>
                  <div class="type-stat-sub">平均评分: {{ stats.repairRating.toFixed(1) }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="type-stat-card cleaning-bg">
                <div class="type-stat-icon">
                  <el-icon><Brush style="font-size: 24px" /></el-icon>
                </div>
                <div class="type-stat-info">
                  <div class="type-stat-title">保洁任务</div>
                  <div class="type-stat-value">{{ stats.cleaningTasks }}</div>
                  <div class="type-stat-sub">平均评分: {{ stats.cleaningRating.toFixed(1) }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row> -->
    
    <!-- 单个工种的详细统计 -->
    <!-- <el-row :gutter="20" style="margin-top: 20px" v-if="userRole && userRole !== '管理员'">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>{{ getTaskTypeName(filterType) }}任务统计</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">本月完成</div>
                <div class="stat-box-value">{{ stats.monthlyCompleted }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">本周完成</div>
                <div class="stat-box-value">{{ stats.weeklyCompleted }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">好评率</div>
                <div class="stat-box-value">{{ stats.goodRatingPercentage }}%</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row> -->
  </div>

  <!-- 任务详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    :title="currentTask.type ? `${getTaskTypeName(currentTask.type)}任务详情` : '任务详情'"
    width="600px"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="任务编号">{{ currentTask.id }}</el-descriptions-item>
      <el-descriptions-item label="任务类型">
        <el-tag :type="getTaskTypeTag(currentTask.type)">{{ getTaskTypeName(currentTask.type) }}</el-tag>
      </el-descriptions-item>
      
      <!-- 送水任务特有字段 -->
      <template v-if="currentTask.type === 'water'">
        <el-descriptions-item label="产品名称">{{ currentTask.product_name }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentTask.quantity }}</el-descriptions-item>
        <el-descriptions-item label="配送地址">{{ currentTask.delivery_address || currentTask.address }}</el-descriptions-item>
      </template>
      
      <!-- 维修任务特有字段 -->
      <template v-if="currentTask.type === 'repair'">
        <el-descriptions-item label="故障描述">{{ currentTask.fault_description || currentTask.content }}</el-descriptions-item>
        <el-descriptions-item label="维修位置">{{ currentTask.location || currentTask.address }}</el-descriptions-item>
      </template>
      
      <!-- 保洁任务特有字段 -->
      <template v-if="currentTask.type === 'cleaning'">
        <el-descriptions-item label="特殊要求">{{ currentTask.special_requirements || currentTask.content || '标准保洁' }}</el-descriptions-item>
        <el-descriptions-item label="服务地址">{{ currentTask.address }}</el-descriptions-item>
      </template>
      
      <!-- 通用字段 -->
      <el-descriptions-item label="联系人">{{ currentTask.contact_name || '无' }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ currentTask.contact_phone || '无' }}</el-descriptions-item>
      <el-descriptions-item label="完成时间">{{ currentTask.completed_time }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentTask.status === '已评价' ? 'success' : 'info'">{{ currentTask.status }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="用户评分">
        <el-rate v-model="currentTask.rating" disabled v-if="currentTask.rating > 0"/>
        <span v-else>暂无评分</span>
      </el-descriptions-item>
      <el-descriptions-item label="评价内容">{{ currentTask.review_content || '暂无评价' }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Finished, Star, Money, StarFilled, MugTea, Service, Brush } from '@element-plus/icons-vue';
import { dashboardService } from '@/api/tasks';

export default {
  name: 'StaffHistory',
  components: {
    Finished,
    Star,
    Money,
    StarFilled,
    MugTea,
    Service,
    Brush
  },
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const completedTasks = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const filterStatus = ref('');
    const ratingFilter = ref('');
    const filterType = ref('');
    const userRole = ref('');
    
    // 详情对话框
    const detailDialogVisible = ref(false);
    const currentTask = ref({});

    // 统计数据
    const stats = reactive({
      totalCompleted: 0,
      totalRated: 0,
      totalAmount: 0,
      averageRating: 0,
      waterTasks: 0,
      waterRating: 0,
      repairTasks: 0,
      repairRating: 0,
      cleaningTasks: 0,
      cleaningRating: 0,
      monthlyCompleted: 0,
      weeklyCompleted: 0,
      goodRatingPercentage: 0
    });

    // 初始化用户角色和任务类型
    const initUserRoleAndTaskType = () => {
      // 从本地存储获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      userRole.value = userInfo.employeeType || '';
      
      // 根据角色自动设置任务类型
      switch(userRole.value) {
        case '送水工':
          filterType.value = 'water';
          break;
        case '保洁工':
          filterType.value = 'cleaning';
          break;
        case '维修工':
          filterType.value = 'repair';
          break;
        default:
          // 默认不筛选
          filterType.value = '';
      }
    };

    // 获取已完成任务列表
    const fetchCompletedTasks = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          type: filterType.value
        };

        console.log('查询参数:', params);
        const { data } = await dashboardService.getCompletedTasks(params);
        if (data.code === 200) {
          // 获取原始数据
          let rawData = data.data.list || data.data;
          
          // 前端筛选逻辑
          let filteredData = rawData;
          
          // 按状态筛选
          if (filterStatus.value) {
            filteredData = filteredData.filter(task => task.status === filterStatus.value);
          }
          
          // 按评分筛选
          if (ratingFilter.value) {
            const ratingValue = parseInt(ratingFilter.value);
            if (ratingValue === 0) {
              // 筛选未评分的任务
              filteredData = filteredData.filter(task => !task.rating || task.rating === 0);
            } else {
              // 筛选特定评分的任务
              filteredData = filteredData.filter(task => task.rating === ratingValue);
            }
          }
          
          // 更新数据和总数
          completedTasks.value = filteredData;
          total.value = filteredData.length;
          
          // 计算统计数据
          calculateStats();
        } else {
          ElMessage.error(data.message || '获取历史记录失败');
        }
      } catch (error) {
        console.error('获取历史记录失败:', error);
        ElMessage.error('获取历史记录失败');
      } finally {
        loading.value = false;
      }
    };

    // 计算统计数据
    const calculateStats = () => {
      // 基础统计
      stats.totalCompleted = total.value;
      
      // 只计算当前页面的评分统计
      const ratedTasks = completedTasks.value.filter(task => task.rating > 0);
      stats.totalRated = ratedTasks.length;
      
      // 计算总金额
      stats.totalAmount = completedTasks.value.reduce((sum, task) => {
        return sum + (task.amount || 0);
      }, 0);
      
      // 计算平均评分
      stats.averageRating = ratedTasks.length > 0 
        ? ratedTasks.reduce((sum, task) => sum + task.rating, 0) / ratedTasks.length 
        : 0;
      
      // 按类型统计
      const waterTasks = completedTasks.value.filter(task => task.type === 'water');
      const repairTasks = completedTasks.value.filter(task => task.type === 'repair');
      const cleaningTasks = completedTasks.value.filter(task => task.type === 'cleaning');
      
      stats.waterTasks = waterTasks.length;
      stats.repairTasks = repairTasks.length;
      stats.cleaningTasks = cleaningTasks.length;
      
      // 各类型平均评分
      const ratedWaterTasks = waterTasks.filter(task => task.rating > 0);
      stats.waterRating = ratedWaterTasks.length > 0 
        ? ratedWaterTasks.reduce((sum, task) => sum + task.rating, 0) / ratedWaterTasks.length 
        : 0;
        
      const ratedRepairTasks = repairTasks.filter(task => task.rating > 0);
      stats.repairRating = ratedRepairTasks.length > 0 
        ? ratedRepairTasks.reduce((sum, task) => sum + task.rating, 0) / ratedRepairTasks.length 
        : 0;
        
      const ratedCleaningTasks = cleaningTasks.filter(task => task.rating > 0);
      stats.cleaningRating = ratedCleaningTasks.length > 0 
        ? ratedCleaningTasks.reduce((sum, task) => sum + task.rating, 0) / ratedCleaningTasks.length 
        : 0;
      
      // 计算时间相关统计
      const now = new Date();
      const currentMonth = now.getMonth();
      const currentYear = now.getFullYear();
      
      // 本月完成的任务
      stats.monthlyCompleted = completedTasks.value.filter(task => {
        if (!task.completed_time) return false;
        const completedDate = new Date(task.completed_time);
        return completedDate.getMonth() === currentMonth && 
               completedDate.getFullYear() === currentYear;
      }).length;
      
      // 获取本周的开始时间（周一）
      const getWeekStart = () => {
        const d = new Date(now);
        const day = d.getDay();
        const diff = d.getDate() - day + (day === 0 ? -6 : 1);
        return new Date(d.setDate(diff));
      };
      
      const weekStart = getWeekStart();
      
      // 本周完成的任务
      stats.weeklyCompleted = completedTasks.value.filter(task => {
        if (!task.completed_time) return false;
        const completedDate = new Date(task.completed_time);
        return completedDate >= weekStart;
      }).length;
      
      // 计算好评率（4星及以上）
      const goodRatings = ratedTasks.filter(task => task.rating >= 4).length;
      stats.goodRatingPercentage = ratedTasks.length > 0
        ? Math.round((goodRatings / ratedTasks.length) * 100)
        : 0;
    };

    // 获取任务类型标签样式
    const getTaskTypeTag = (type) => {
      const map = {
        'water': 'primary',
        'cleaning': 'success',
        'repair': 'warning'
      };
      return map[type] || 'info';
    };

    // 获取任务类型名称
    const getTaskTypeName = (type) => {
      const map = {
        'water': '送水',
        'cleaning': '保洁',
        'repair': '维修'
      };
      return map[type] || '未知';
    };

    // 查看任务详情
    const viewTaskDetail = async (task) => {
      try {
        // 先设置基本信息
        currentTask.value = {...task};
        
        // 如果有任务ID，尝试从后端获取完整信息
        if (task.id) {
          loading.value = true;
          try {
            // 尝试获取详细信息
            const { data } = await dashboardService.getTaskDetail(task.id, 'water');
            if (data.code === 200 && data.data) {
              // 合并详细信息
              const detailData = data.data;
              currentTask.value = {
                ...currentTask.value,
                contact_name: detailData.contact_name || currentTask.value.contact_name || '未指定',
                contact_phone: detailData.contact_phone || currentTask.value.contact_phone || '未指定',
                product_name: detailData.product_name || currentTask.value.product_name || '',
                quantity: detailData.quantity || currentTask.value.quantity || '',
                total_amount: detailData.total_amount || currentTask.value.total_amount || 0,
                delivery_address: detailData.delivery_address || currentTask.value.address || '',
                completed_time: detailData.actual_delivery_time || currentTask.value.completed_time || '',
                rating: detailData.rating || currentTask.value.rating || 0,
                review_content: detailData.review_content || currentTask.value.review_content || ''
              };
            }
          } catch (error) {
            console.error('获取任务详情失败:', error);
            // 即使获取详情失败，也继续显示已有信息
            
            // 如果没有product_name和quantity，尝试从content解析
            if ((!currentTask.value.product_name || !currentTask.value.quantity) && currentTask.value.content) {
              const contentParts = currentTask.value.content.split(' x');
              if (contentParts.length === 2) {
                currentTask.value.product_name = contentParts[0];
                currentTask.value.quantity = contentParts[1];
              }
            }
          } finally {
            loading.value = false;
          }
        } else {
          // 如果没有任务ID，尝试从content解析产品信息
          if ((!currentTask.value.product_name || !currentTask.value.quantity) && currentTask.value.content) {
            const contentParts = currentTask.value.content.split(' x');
            if (contentParts.length === 2) {
              currentTask.value.product_name = contentParts[0];
              currentTask.value.quantity = contentParts[1];
            }
          }
        }
        
        // 显示详情对话框
        detailDialogVisible.value = true;
      } catch (error) {
        console.error('处理任务详情失败:', error);
        ElMessage.error('获取任务详情失败');
      }
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1; // 重置为第一页
      fetchCompletedTasks();
    };

    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchCompletedTasks();
    };

    // 重置筛选条件
    const resetFilters = () => {
      filterStatus.value = '';
      ratingFilter.value = '';
      currentPage.value = 1;
      fetchCompletedTasks();
    };

    onMounted(() => {
      initUserRoleAndTaskType();
      fetchCompletedTasks();
    });

    return {
      loading,
      completedTasks,
      total,
      currentPage,
      pageSize,
      filterStatus,
      ratingFilter,
      filterType,
      userRole,
      stats,
      detailDialogVisible,
      currentTask,
      fetchCompletedTasks,
      getTaskTypeTag,
      getTaskTypeName,
      viewTaskDetail,
      handleSizeChange,
      handleCurrentChange,
      resetFilters
    };
  }
};
</script>

<style scoped>
.history-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.stat-card {
  height: 90px;
  margin-bottom: 5px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  margin-right: 15px;
}

.water-icon {
  background-color: #409EFF;
}

.repair-icon {
  background-color: #E6A23C;
}

.cleaning-icon {
  background-color: #67C23A;
}

.rating-icon {
  background-color: #F7BA2A;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

/* 按类型统计卡片样式 */
.type-stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  color: white;
  height: 120px;
}

.water-bg {
  background: linear-gradient(135deg, #409EFF, #53a8ff);
}

.repair-bg {
  background: linear-gradient(135deg, #E6A23C, #f0b95a);
}

.cleaning-bg {
  background: linear-gradient(135deg, #67C23A, #85ce61);
}

.type-stat-icon {
  font-size: 40px;
  margin-right: 20px;
}

.type-stat-info {
  display: flex;
  flex-direction: column;
}

.type-stat-title {
  font-size: 16px;
  margin-bottom: 5px;
}

.type-stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.type-stat-sub {
  font-size: 14px;
  opacity: 0.8;
}

/* 单个工种统计样式 */
.stat-box {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-box-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-box-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}
</style> 